<template>
  <a-form
    :model="ruleForm"
    :rules="rules"
    v-bind="layout"
    @finish="handleFinish"
  >
    <a-form-item has-feedback label="名称" name="name">
      <a-input v-model:value="ruleForm.name" />
    </a-form-item>
    <a-form-item label="权限" name="permission">
      <a-transfer
        :data-source="permissions"
        :titles="['可用权限', '选中的权限']"
        :target-keys="targetPermissionKeys"
        :selected-keys="selectedPermissionKeys"
        :render="(item) => item.title"
        @change="handleChange"
        @selectChange="handleSelectChange"
        :locale="{
          itemUnit: '项',
          itemsUnit: '项',
          notFoundContent: '列表为空',
          searchPlaceholder: '请输入搜索内容',
        }"
      />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'

export default {
  name: 'AddOrEditUserGroup',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  data() {
    // validStr不包含空格
    let isValidStr = (str) => {
      return str.indexOf(' ') === -1
    }
    let validateName = async (rule, value) => {
      if (value === '') {
        return Promise.reject('请输入名称')
      } else {
        if (!isValidStr(value)) {
          return Promise.reject('名称含有非法字符')
        }
        return Promise.resolve()
      }
    }
    return {
      ruleForm: {
        name: '',
      },
      rules: {
        name: [
          {
            validator: validateName,
            trigger: 'change',
            required: true,
            whitespace: true,
          },
        ],
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      submitting: false,
      permissions: [],
      targetPermissionKeys: [],
      selectedPermissionKeys: [],
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    fetch() {
      this.axios
        .get('/user_management/permissions/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; i++) {
            this.permissions.push({
              key: data[i].url,
              title: data[i].name,
            })
          }
          if (this.url !== '') {
            this.axios
              .get(this.url)
              .then((res) => {
                const data = res.data
                this.ruleForm.name = data.name
                this.targetPermissionKeys = data.permissions
              })
              .catch((error) => {
                console.log('Error', error.message)
              })
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
    },
    handleFinish(values) {
      this.submitting = true
      const formData = new FormData()
      formData.append('name', values.name)
      this.targetPermissionKeys.forEach((permission) => {
        formData.append('permissions', permission)
      })
      if (this.url !== '') {
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/user_management/groups/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
    handleChange(nextTargetKeys) {
      this.targetPermissionKeys = nextTargetKeys
    },
    handleSelectChange(sourceSelectedKeys, targetSelectedKeys) {
      this.selectedPermissionKeys = [
        ...sourceSelectedKeys,
        ...targetSelectedKeys,
      ]
      // console.log('sourceSelectedKeys: ', sourceSelectedKeys)
      // console.log('targetSelectedKeys: ', targetSelectedKeys)
    },
  },
}
</script>
